<?php
namespace app\common\entity;

use app\common\shop\UserAgentLevelModel;
use app\common\shop\UserHouseLevelModel;
use think\Db;
use think\Model;

class GameRoomLog extends Model
{
    protected $table = 'game_room_log';

    protected $autoWriteTimestamp = false;

    static public function addNew($redis,$room_id,$num){
        $old = self::where('room_id',$room_id)->order('id desc')->find();
        $roomInfo = GameRoom::where('id',$room_id)->find();
        if($num == 1){
            $period = $room_id.$old['id'].$num;
        }else{
            $period = $room_id.($old['id']+1).$num;
        }
        $data = [
            'period'=>$period,
            'date'=>date('Ymd'),
            'num'=>$num,
            'room_id'=>$room_id,
            'is_acitve'=>1,
            'create_time'=>time(),
        ];
        $insert = self::insertGetId($data);
        return $insert;
    }

    /**
     * 游戏结束
     * @param $redis
     * @param $room_id
     * @return int|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    static public function edit($redis,$room_id){
        if(!$redis['users']){return false;}
        foreach($redis['users'] as $k=>$v){
            if($v['award'] > 0){

                MywalletLog::addLog($v['uid'],$v['award'],1,'游戏抽中福币',14,1,$redis['log_id']);
            }

            $item = [
                'uid'=>$v['uid'],
                'room_id'=>$room_id,
                'room_log_id'=>$redis['log_id'],
                'status'=>$v['status'],
                'award'=>$v['award'],
                'create_time'=>time()
            ];

            GameUserLog::addNew($item);
        }
        $update = self::where('id',$redis['log_id'])->update(['end_time'=>time(),'result'=>json_encode($redis)]);
        return $update;
    }

    /**
     * 收益
     * @param $userInfo
     * @param $room_id
     * @param $log_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function profit($userInfo,$room_id,$log_id,$order_num,$ordersn){
        //if(!self::is_robot($userInfo['uid'])){echo $order_num."award\n";}
        if(self::is_robot($userInfo['uid']))return false;

        //代理商
        $user = User::where('id',$userInfo['uid'])->find();
        $userlist = User::where('status',1)->field('id,mobile,pid,agent_level')->where('agent_over_time','>',time())->select();

        if (!empty($userlist)) {

            $list = self::fanTree(User::field('id,mobile,pid,agent_level')->select(), $user['pid'], $user['agent_level']);//上级代理商们
            print_r($list);
            $list = self::get_agent($list, $user['agent_level']);
            $user_agent_level = UserAgentLevelModel::select();
            $level = $user['agent_level'];
            print_r($list);
            foreach ($list as $k => $v) {
                if($v['agent_level'] > 0 && $v['agent_level'] >= $level) {
                    echo "代理uid:".$v['id']." 代理等级:".$v['agent_level']."\n";
                    foreach ($user_agent_level as $key => $val) {
                        if($v['agent_level'] == $val['id']){
                            $money = bcmul(bcmul($val[$v['type']], 0.01, 4), $order_num,4);


                            //MywalletLog::addLog($v['id'], $money, 4, '代理商' . $val['name'].$v['type_name'].' 订单号：'.$ordersn, 13, 1, $log_id);
                            MywalletLog::addLog($v['id'], $money, 4, $val['name'].'奖励', 13, 1, $log_id);

                            continue;
                        }
                    }
                }
            }
        }


        /* //房主
         $roomInfo = GameRoom::where('id',$room_id)->find();
         $house = User::where('house_level','>=',$roomInfo['size'])->field('id,house_level')->select();//房主们
         $profit_config = Config::getValue('room_profit');



         if(!empty($house)){
             $profit_num = bcdiv(bcmul($profit_config,0.01,4),count($house),8);
             foreach($house as $k=>$v){
                     $my_percent = $profit_num;
                     $money = bcmul($my_percent,$userInfo['award'],6);
                     echo $money."\n";
                     MywalletLog::addLog($v['id'], $money, 1, '', 15, 1, $log_id);
             }
         }*/
    }

    static public function get_agent($list,$level){
        $users = [];
        $level = $level;
        $ping = false;
        foreach($list as $v) {
            //奖励
            if ($v['agent_level'] > $level) {
                $v['type'] = 'percentage';
                $v['type_name'] = '佣金';
                array_push($users, $v);
                $level = $v['agent_level'];
                $ping = false;
            }
            //平级
            elseif ($v['agent_level'] > 0 && $level == $v['agent_level'] && $ping == false) {
                $v['type'] = 'peers';
                $v['type_name'] = '平级奖';
                array_push($users, $v);
                $ping = true;
            }
        }
        return $users;
    }

    /**
     * 判断是不是机器人
     * @param $uid
     * @return bool
     */
    static public function is_robot($uid){
        if(!$uid){
            return false;
        }
        $robot = User::where('id',$uid)->where('robot',1)->find();
        return $robot?true:false;
    }
    /**
     * 获取上级代理商
     * @param $data
     * @param $id
     * @return array
     */
    static public function fanTree($data, $id,$level){
        $list = array();
        foreach($data as $v) {
            if($v['id'] == $id ) {

                $item = self::fanTree($data, $v['pid'], $v['agent_level']);
                array_push($list, $v);
                if (!empty($item)) {
                    $list = array_merge($list, $item);
                }
                /* if($level < $v['agent_level'] || $level == 0) {

                     $v['type'] = 'percentage';
                     $v['type_name'] = '佣金';
                     $item = self::fanTree($data, $v['pid'], $v['agent_level']);
                     array_push($list, $v);
                     if (!empty($item)) {
                         $list = array_merge($list, $item);
                     }
                 }else{
                     if($v['agent_level'] > 0 && $level == $v['agent_level']){

                         $v['type'] = 'peers';
                         $v['type_name'] = '平级奖';
                         array_push($list, $v);
                     }
                 }*/

            }
        }
        return $list;
    }




    static public function room_rpofit($money,$log_id){

        if($money <= 0)return true;
        $roomLogInfo = self::where('id',$log_id)->find();
        //房主
        $roomInfo = GameRoom::where('id',$roomLogInfo['room_id'])->find();

        $house = User::where('house_level','>=',$roomInfo['size'])->field('id,house_level')->select();//房主们
        if(count($house) == 0){
            return true;
        }

        $profit_config = GameRoomConfig::where('size',$roomInfo['size'])->value('percentage');

        $money = bcmul($money,bcmul($profit_config,0.01,4),4);

        $profit_num = bcdiv($money,count($house),4);

        foreach($house as $k=>$v){
            print_R($profit_num);echo "money\n\n\n";
            $size = '';
            switch ($v['house_level']){
                case 1:
                    $size = '小房主';
                    break;
                case 2:
                    $size = '中房主';
                    break;
                case 3:
                    $size = '大房主';
                    break;
            }
            MywalletLog::addLog($v['id'], $profit_num, 4, $size, 15, 1, $log_id);
        }

    }

}